/*
This softtware use BSD licence (http://opensource.org/licenses/BSD-3-Clause)

Copyright (c) 2013, Martin Lebeda
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the Martin Lebeda nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package cz.lebeda.bas;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Provide tmp for different sizes of backuped files.
 * For smaller files only in memory, for larger provide tmp buffer on disk.
 *
 * @author <a href="mailto:martin.lebeda@gmail.com">Martin Lebeda</a>
 *         Date: 25.11.13
 */
public class TmpContent {

    final Logger logger = LoggerFactory.getLogger(TmpContent.class);

    /**
     * Define buffersize hold in memory
     */
    public static final int BUFFER_SIZE = 200 /* MB */ * 1024 * 1024; // 10MB

    private File tmpFile = null;
    private final boolean fileLarge;
    private final long size;
    private ByteArrayOutputStream byteArrayOutputStream;

    /**
     * Create tmp buffer provider instance.
     *
     * @param voBackupFile backuped file metadata
     */
    public TmpContent(VOBackupFile voBackupFile) {
        fileLarge = TmpContent.isFileLarge(voBackupFile);
        size = voBackupFile.getSize();
        if (fileLarge) {
            tmpFile = new File(
                    FileUtils.getTempDirectoryPath() + File.separator + UUID.randomUUID().toString() + ".bas");
        }
    }

    /**
     * Clear all caches or delete disk temporary file.
     *
     * @throws IOException if cannot delete temporary file on disk
     */
    public void clear() throws IOException {
        if ((tmpFile != null) && tmpFile.exists()) {
            FileUtils.forceDelete(tmpFile);
        } else {
            byteArrayOutputStream = null;
        }
    }

    /**
     * Identify if file is big. This is by compare to BUFFER_SIZE constant.
     *
     * @param voBackupFile backupd file metadata
     * @return true if file is large
     */
    static boolean isFileLarge(VOBackupFile voBackupFile) {
        return voBackupFile.getSize() > BUFFER_SIZE;
    }

    /**
     * Provide output strem implemented on disk or in memory depends on the filesize.
     *
     * @return instance of output stream
     * @throws FileNotFoundException
     */
    public OutputStream getOutputStrem() throws FileNotFoundException {
        OutputStream fos;
        if (fileLarge) {
            logger.trace("use tmp file");
            fos = new FileOutputStream(tmpFile);
        } else {
            logger.trace("use memory");
            byteArrayOutputStream = new ByteArrayOutputStream((int)size);
            fos = byteArrayOutputStream;
        }
        return fos;
    }

    public boolean isLarge() {
        return fileLarge;
    }

    /**
     * get md5sum of buffer content
     *
     * @return
     * @throws IOException
     */
    public String getMd5Sum() throws IOException {
        String sumMd5;
        InputStream fis = getInputStream();
        sumMd5 = DigestUtils.md5Hex(fis);
        fis.close();
        return sumMd5;
    }

    /**
     * Provide instance of inputstream for read content of backuped file.
     *
     * @return instance of inputstream
     * @throws FileNotFoundException
     */
    public InputStream getInputStream() throws FileNotFoundException {
        InputStream fis;
        if (fileLarge) {
           fis = new FileInputStream(tmpFile);
        } else {
           fis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        }
        return fis;
    }
}
